package com.ldg.user.controller;

import com.ld.pojo.R;
import com.ldg.user.client.ManagerClient;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;


@Controller
@RefreshScope  //修改配置中心配置后不用重启
public class IndexController {
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ManagerClient managerClient;
//	@Value("${user.name}")
	private String username;


	@GetMapping({"/","/register"})
	public String register(){

		return "register";
	}

	//1. 使用restTemplate实现微服务的调用
	@GetMapping("/user/findBrands")
	@ResponseBody
	public R findBrands(){
		R r = restTemplate.getForObject("http://ldg-manager/brand/findAll", R.class);
		return r;
	}

	//2. 使用openfeign实现微服务的调用
	@GetMapping("/user/brand/findAll")
	@ResponseBody
	public R findBrands2(){
		return managerClient.findAll();
	}

	//3. 使用openfeign实现微服务的调用
	@GetMapping("/user/brand/info/{id}")
	@ResponseBody
	public R findById(@PathVariable String id){
		return managerClient.info(id);
	}


	@GetMapping("/user/read/config")
	@ResponseBody
	public R readConfig(){
		return R.ok().put("name",username);
	}

	//4. 默认主页
	@GetMapping("/user/index")
	public String index(HttpSession session, Model model){
		// 得到登录名
		Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
		if(assertion != null){
			String name = assertion.getPrincipal().getName();
			model.addAttribute("name",name);
		}
		return "home-index";
	}

	@GetMapping("/user/logout")
	public String logout(HttpSession session){
		session.removeAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
		session.invalidate();
		return "redirect:http://localhost:8080/cas/logout?service=http://localhost:9005/user/login";
	}

	// 登录导向
	@GetMapping("/user/login")
	public String login(){
		return "login";
	}
}
